package com.liuyi.netty.mqtt;

import com.liuyi.netty.mqtt.channel.MqttChannelInitializer;
import com.liuyi.netty.mqtt.configution.MqttBeanManage;
import com.liuyi.netty.mqtt.processed.store.impl.MemoryMqttSessionStore;
import com.liuyi.netty.mqtt.server.AuthServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * Mqtt 服务器 Broker
 * <pre>
 *     启动入口 {@linkplain #main(String[])}
 * </pre>
 *
 * @author Mr.Fmy
 * @since 2021-08-19
 */
@Slf4j
public class MqttServer {

    private int port;

    public MqttServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        int port = 1883;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }

        new MqttServer(port).run();
    }

    public void run() throws Exception {
        MqttBeanManage mqttBeanManage = new MqttBeanManage(new AuthServer() {
        }, new MemoryMqttSessionStore());
        mqttBeanManage.start();
        //创建线程组 boos 和 worker
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //创建服务器启动 Bootstrap
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // 指定为NIO通道
                    .childHandler(new MqttChannelInitializer())
                    .option(ChannelOption.SO_BACKLOG, 128)          // (5)
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync(); // (7)
            log.info("Mqtt Server Start Success");
            // Wait until the server socket is closed.
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
